package jtacck.labmedicine;

import java.util.List;

import jtacck.labmedicine.Cache.ChecklistState;
import jvm.jtacck.db.records.ClientSite;
import jvm.jtacck.db.records.Hospital;
import jvm.jtacck.db.records.Item;
import jvm.jtacck.db.records.ShippingInformation;
import jvm.jtacck.db.records.Specimen;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
 * Displays a list that can be checked and a button to go to the next screen
 * only if all items are checked.
 * 
 * @author Kevin
 * 
 */
public class ChecklistActivity extends Activity {
    private OnItemClickListener listener;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private int currentPosition;
    private ChecklistState state;

    /**
     * Called when ChecklistActivity is started. Requires a Bundle named
     * "jtacck" as an extra to the Activity's intent. Bundle jtacck must
     * include: A StringArray with key "toDo" that represents the checklist
     * contents. A Class<?> stored as a Serializable with key "nextActivity"
     * that is the Activity that will start when the checklist is completed. A
     * Serializable with key "serverRequest" that is the message if any) sent to
     * the server when an item is clicked. A boolean with key "conditional" that
     * states if the checklist is related to another Activity. (defaults to
     * false if not included)
     * 
     * @Override
     */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle extras = this.getIntent().getBundleExtra("jtacck");
        setContentView(R.layout.checklist_list_layout);
        listView = (ListView) findViewById(R.id.instruction_view);
        String[] toDo;
        Button scanButton = (Button) findViewById(R.id.scan_button);
        scanButton.setVisibility(View.GONE);
        OnClickListener barcodeListener = new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(
                        "com.google.zxing.client.android.SCAN");
                startActivityForResult(intent, 0);
            }
        };
        state = MainActivity.cache.strToEnum(extras.getString("state"));
        // if(extras.getString("state") != null) {
        switch (state) {
        case START:
            toDo = MainActivity.cache.startRoute();
            break;
        case END:
            toDo = MainActivity.cache.endRoute();
            break;
        case SITE:
            toDo = MainActivity.cache.arriveSite((ClientSite) extras
                    .getSerializable("serverRequest"));
            break;
        case ROUTE:
            toDo = MainActivity.cache.arriveHosp((Hospital) extras
                    .getSerializable("serverRequest"));
            break;
        case SHIPPING:
            toDo = MainActivity.cache.getPackages();
            refresh();
            listener = new OnItemClickListener() {
                public void onItemClick(AdapterView<?> adview, View view,
                        int position, long id) {

                    Bundle params = new Bundle();
                    ShippingInformation shippingInfo = MainActivity.cache
                            .getPackageById(position);
                    Specimen specimen = shippingInfo.specimen;

                    String[] contents = new String[specimen.contents.size()];
                    Item[] content = specimen.contents.toArray(new Item[0]);
                    for (int i = 0; i < contents.length; i++)
                        contents[i] = content[i].name;

                    params.putStringArray("contents", contents);
                    params.putInt("selectedID", position);
                    params.putString("barcode", specimen.barcode);
                    params.putString("requirements", specimen.requirements);
                    params.putString("title", specimen.description);
                    params.putBoolean("collected", MainActivity.cache
                            .isChecked(state).get(position));

                    Intent intent = new Intent(ChecklistActivity.this,
                            (Class<?>) extras.getSerializable("forResult"));
                    intent.putExtra("jtacck", params);

                    listView.setItemChecked(position, false);

                    startActivityForResult(intent, position + 1);
                }
            };
            listView.setOnItemClickListener(listener);
            scanButton.setOnClickListener(barcodeListener);
            scanButton.setVisibility(View.VISIBLE);
            break;
        default:
            toDo = new String[0];
        }
        // }else
        // toDo = extras.getStringArray("toDo");

        adapter = new ArrayAdapter<String>(this, R.layout.checklist, toDo);
        listView.setAdapter(adapter);

        View button = findViewById(R.id.to_shipping_button);
        button.setOnClickListener(new ChecklistListener(this, (Class<?>) extras
                .getSerializable("nextActivity"), MainActivity.cache
                .strToEnum(extras.getString("state")), extras
                .getSerializable("serverRequest")));
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        refresh();

        // if (extras.getBoolean("conditional", false)) {
        // refresh();
        // listener = new OnItemClickListener() {
        // public void onItemClick(AdapterView<?> adview, View view,
        // int position, long id) {
        //
        // Bundle params = new Bundle();
        // ShippingInformation shippingInfo = MainActivity.sList.shippingList
        // .get(position);
        // Specimen specimen = shippingInfo.specimen;
        //
        // String[] contents = new String[specimen.contents.size()];
        // Item[] content = specimen.contents.toArray(new Item[0]);
        // for (int i = 0; i < contents.length; i++)
        // contents[i] = content[i].name;
        //
        // params.putStringArray("contents", contents);
        // params.putInt("selectedID", position);
        // params.putString("barcode", specimen.barcode);
        // params.putString("requirements", specimen.requirements);
        // params.putString("title", specimen.description);
        // params.putBoolean("collected",
        // shippingInfo.status.status_id >= 2);
        //
        // Intent intent = new Intent(ChecklistActivity.this,
        // (Class<?>) extras.getSerializable("forResult"));
        // intent.putExtra("jtacck", params);
        //
        // listView.setItemChecked(position, false);
        //
        // startActivityForResult(intent, position + 1);
        // }
        // };

        /* } else */if (extras.getBoolean("freeform", true)) {
            currentPosition = 0;
            OnItemClickListener listen = new OnItemClickListener() {
                public void onItemClick(AdapterView<?> adview, View view,
                        int position, long id) {
                    if (position > currentPosition)
                        listView.setItemChecked(position,
                                !listView.isItemChecked(position));
                    else if (position == currentPosition) {
                        if (listView.isItemChecked(position))
                            currentPosition++;
                        else
                            currentPosition--;
                    } else if (position + 1 == currentPosition) {
                        currentPosition--;
                        listView.setItemChecked(position, false);
                    } else
                        listView.setItemChecked(position, true);
                }
            };
            listView.setOnItemClickListener(listen);
        }
    }

    /**
     * Result from conditional checklist items are sent here.
     */
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                for (int i = 0; i < adapter.getCount(); i++) {
                    if (contents
                            .equals(MainActivity.cache.getPackageById(i).specimen.barcode))
                        listener.onItemClick(null, null, i, i);
                }

            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
        if (resultCode <= 0) {
            listView.setItemChecked(-resultCode, false);
        } else
            listView.setItemChecked(requestCode - 1, true);
        refresh();
    }

    private void refresh() {
        List<Boolean> checked = MainActivity.cache.isChecked(state);
        if (checked != null)
            for (int i = 0; i < checked.size(); i++)
                listView.setItemChecked(i, checked.get(i));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreateDialog(int)
     * 
     * Creates the actual dialog.
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 1:
            return SharedMethods.logoutAlert(this);
        }
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.text:
            showDialog(1);
            break;
        case R.id.icontext:
            break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        final Bundle extras = this.getIntent().getBundleExtra("jtacck");

        ListView listView = (ListView) this.findViewById(R.id.instruction_view);

        boolean allChecked = true;
        for (int i = 0; i < listView.getCount(); i++) {
            allChecked = allChecked && listView.isItemChecked(i);
        }

        if (keyCode == KeyEvent.KEYCODE_BACK
                && MainActivity.cache.strToEnum(extras.getString("state"))
                        .equals(Cache.ChecklistState.SHIPPING) && !allChecked) {
            Toast.makeText(this, "Please complete the check list",
                    Toast.LENGTH_SHORT).show();
            return true;
        }
        super.onKeyDown(keyCode, event);
        return true;
    }

}
